package org.example.classdemo.parameterizedtype;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * shift+F2跳到错误
 * 假设有个List
 * Class->List.class对象本身
 * Type->描述这个变量的类型,包括路径java.util.List以及泛型等信息
 * ParameterizedType->特殊的Type,也叫参数化类型,特征是带了泛型,所以叫参数化
 */
public class ParameterizedBean {
    ArrayList<String> list1;
    List list2;
    Map<String,Integer> map1;
    Map map2;
    Map.Entry<Long,String> map3;

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Map<String, String> map = new HashMap<String, String>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        map.put("key3", "value3");
        map.entrySet().forEach(v-> System.out.println(v.getKey()+":"+v.getValue()));

        Field[] declaredFields = ParameterizedBean.class.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            //declaredField.getType() 返回class对象
            //declaredField.getGenericType()返回Type类型,如果带泛型则就是参数化Type类型
            Boolean isParameterizedType = declaredField.getGenericType() instanceof ParameterizedType;
            System.out.println(declaredField.getName()+":"+isParameterizedType);
            if(isParameterizedType){
                Type[] actualTypeArguments = ((ParameterizedType) declaredField.getGenericType()).getActualTypeArguments();
                Class<?> x = Class.forName(actualTypeArguments[0].getTypeName());
                Object o = x.newInstance();
                System.out.println(o);
                //比如Map.Entry<Long,String>就会返回java.util.Map
                ((ParameterizedType) declaredField.getGenericType()).getOwnerType();
                //比如Map.Entry<Long,String>就会返回java.util.Map$Entry
                ((ParameterizedType) declaredField.getGenericType()).getRawType();
            }
        }
    }
}
